import { getQueryVariable } from '@/utils/common.js'
import { mapMutations } from 'vuex'

export default {
  data() {
    return {
      
    }
  },
  onLaunch() {
    // 当前项目不嵌入app
    if (!getApp().globalData.isAppConfig) {
      return
    }

    console.log('window.location.href :>> ', window.location.href)
    const versioncode = getQueryVariable('versioncode')
    if (!versioncode) {
      return
    }

    uni.setStorageSync('isFromApp', '1')
    getApp().globalData.isFromApp = '1'
    getApp().globalData.appVersionCode = versioncode
    const systemInfo = uni.getSystemInfoSync()
    const { model } = systemInfo
    if (!model) {
      return
    }

    // 获取app消息处理
    this.receiveCappMessageHandler(model)
    
  },
  created() {
    
  },
  methods: {
    ...mapMutations(['login', 'clearLoginInfo']),
    receiveCappMessageHandler(model) {
      if (model.includes('iPhone')) {
        window.addEventListener('message', (event) => {
          uni.$emit('receiveCappMessage', event)
        })
      } else {
        document.addEventListener('message', (event) => {
          uni.$emit('receiveCappMessage', event)
        })
      }
      uni.$on('receiveCappMessage', (data) => {
        const result = JSON.parse(data.data)
        if (result.msgType === 'initUserInfo') {
          this.receiveMessage(result)
        }
      })
    },
    receiveMessage(optionsData) {
      if (optionsData.gateWayData && optionsData.gateWayData.tokenid) {
        uni.setStorageSync(
          'tokenid',
          'lll',
        )
        this.login(optionsData.loginData)
        uni.$emit('onLogin', {
          data: {
            onLogin: true,
            ...optionsData.loginData,
          },
        })
      } else {
        uni.$emit('onLogin', {
          data: {
            onLogin: false,
          },
        })
        this.clearLoginInfo()
      }
    },
  },
}